const { I18nDataModel } = require('../models');
const { getDb } = require('../database');

class I18nService {
  constructor() {
    this.i18nDataModel = new I18nDataModel();
  }

  // 获取国际化数据列表（支持分页与条件）
  async getI18nList(filters) {
    try {
      const { code, message, languageTag, current = 1, currentSize = 10 } = filters;
      const page = parseInt(current, 10);
      const pageSize = parseInt(currentSize, 10);
      const offset = (page - 1) * pageSize;

      const db = await getDb();
      let query = 'SELECT * FROM i18n_data WHERE 1=1';
      const params = [];

      if (code) {
        query += ' AND code LIKE ?';
        params.push(`%${code}%`);
      }
      if (message) {
        query += ' AND message LIKE ?';
        params.push(`%${message}%`);
      }
      if (languageTag) {
        query += ' AND language_tag = ?';
        params.push(languageTag);
      }

      query += ' LIMIT ? OFFSET ?';
      params.push(pageSize, offset);

      const i18nData = await db.all(query, params);

      let totalQuery = 'SELECT COUNT(*) as count FROM i18n_data WHERE 1=1';
      const totalParams = [];
      if (code) {
        totalQuery += ' AND code LIKE ?';
        totalParams.push(`%${code}%`);
      }
      if (message) {
        totalQuery += ' AND message LIKE ?';
        totalParams.push(`%${message}%`);
      }
      if (languageTag) {
        totalQuery += ' AND language_tag = ?';
        totalParams.push(languageTag);
      }

      const total = await db.get(totalQuery, totalParams);

      return {
        success: true,
        data: {
          records: i18nData,
          total: total.count
        },
        message: '获取成功'
      };
    } catch (error) {
      console.error('获取国际化数据列表服务错误:', error);
      return {
        success: false,
        error: error.message,
        message: '获取失败，请稍后重试'
      };
    }
  }

  // 创建国际化数据
  async createI18nData(code, remarks, languageTexts) {
    try {
      if (!code || !languageTexts || !Array.isArray(languageTexts) || languageTexts.length === 0) {
        return {
          success: false,
          message: '代码和语言文本不能为空',
          status: 400
        };
      }
      for (const text of languageTexts) {
        if (!text.languageTag || !text.message) {
          return {
            success: false,
            message: '语言标签和文本不能为空',
            status: 400
          };
        }
      }

      const db = await getDb();
      await db.run('BEGIN TRANSACTION');
      try {
        for (const text of languageTexts) {
          await db.run(
            'INSERT OR REPLACE INTO i18n_data (code, language_tag, message, remarks) VALUES (?, ?, ?, ?)',
            [code, text.languageTag, text.message, remarks]
          );
        }
        await db.run('COMMIT TRANSACTION');
        return {
          success: true,
          data: { code },
          message: '创建成功'
        };
      } catch (error) {
        await db.run('ROLLBACK TRANSACTION');
        throw error;
      }
    } catch (error) {
      console.error('创建国际化数据服务错误:', error);
      return {
        success: false,
        error: error.message,
        message: error.message || '创建失败',
        status: 500
      };
    }
  }

  // 更新国际化数据（按code覆盖）
  async updateI18nData(code, remarks, languageTexts) {
    try {
      if (!code || !languageTexts || !Array.isArray(languageTexts)) {
        return {
          success: false,
          message: '代码和语言文本不能为空',
          status: 400
        };
      }
      for (const text of languageTexts) {
        if (!text.languageTag || !text.message) {
          return {
            success: false,
            message: '语言标签和文本不能为空',
            status: 400
          };
        }
      }

      const db = await getDb();
      await db.run('BEGIN TRANSACTION');
      try {
        await db.run('DELETE FROM i18n_data WHERE code = ?', [code]);
        for (const text of languageTexts) {
          await db.run(
            'INSERT INTO i18n_data (code, language_tag, message, remarks) VALUES (?, ?, ?, ?)',
            [code, text.languageTag, text.message, remarks]
          );
        }
        await db.run('COMMIT TRANSACTION');
        return {
          success: true,
          data: { code },
          message: '更新成功'
        };
      } catch (error) {
        await db.run('ROLLBACK TRANSACTION');
        throw error;
      }
    } catch (error) {
      console.error('更新国际化数据服务错误:', error);
      return {
        success: false,
        error: error.message,
        message: error.message || '更新失败',
        status: 500
      };
    }
  }

  // 删除国际化数据（按code）
  async deleteI18nData(code) {
    try {
      if (!code) {
        return {
          success: false,
          message: '代码不能为空',
          status: 400
        };
      }
      const db = await getDb();
      await db.run('DELETE FROM i18n_data WHERE code = ?', [code]);
      return { success: true, message: '删除成功' };
    } catch (error) {
      console.error('删除国际化数据服务错误:', error);
      return {
        success: false,
        error: error.message,
        message: '删除失败，请稍后重试',
        status: 500
      };
    }
  }

  // 获取指定语言的国际化数据
  async getI18nDataByLanguageTag(languageTag) {
    try {
      if (!languageTag) {
        return { success: false, message: '语言标签不能为空', status: 400 };
      }
      const db = await getDb();
      const i18nData = await db.all('SELECT code, message FROM i18n_data WHERE language_tag = ?', [languageTag]);
      const result = {};
      i18nData.forEach(item => { result[item.code] = item.message; });
      return { success: true, data: result, message: '获取成功' };
    } catch (error) {
      console.error('获取指定语言的国际化数据服务错误:', error);
      return { success: false, error: error.message, message: '获取失败，请稍后重试', status: 500 };
    }
  }

  // 导入国际化数据（JSON/CSV）
  async importI18nData({ format = 'json', items, content }) {
    try {
      const db = await getDb();
      const records = [];

      if (format === 'json') {
        if (!items || !Array.isArray(items) || items.length === 0) {
          return { success: false, message: '导入数据不能为空', status: 400 };
        }
        for (const item of items) {
          const { code, remarks, languageTexts } = item;
          if (!code || !languageTexts || !Array.isArray(languageTexts) || languageTexts.length === 0) {
            return { success: false, message: '代码和语言文本不能为空', status: 400 };
          }
          records.push({ code, remarks, languageTexts });
        }
      } else if (format === 'csv') {
        if (!content || typeof content !== 'string') {
          return { success: false, message: 'CSV内容不能为空', status: 400 };
        }
        // 解析CSV：header: code,languageTag,message,remarks
        const lines = content.trim().split(/\r?\n/);
        const header = lines.shift();
        const cols = header.split(',').map(s => s.trim());
        const idx = {
          code: cols.indexOf('code'),
          languageTag: cols.indexOf('languageTag'),
          message: cols.indexOf('message'),
          remarks: cols.indexOf('remarks')
        };
        const map = new Map();
        for (const line of lines) {
          if (!line.trim()) continue;
          const parts = line.split(',');
          const code = parts[idx.code]?.trim();
          const languageTag = parts[idx.languageTag]?.trim();
          const message = parts[idx.message]?.trim();
          const remarks = parts[idx.remarks]?.trim();
          if (!code || !languageTag || !message) continue;
          const item = map.get(code) || { code, remarks, languageTexts: [] };
          item.remarks = item.remarks || remarks;
          item.languageTexts.push({ languageTag, message });
          map.set(code, item);
        }
        records.push(...map.values());
      } else {
        return { success: false, message: '不支持的导入格式', status: 400 };
      }

      await db.run('BEGIN TRANSACTION');
      try {
        for (const item of records) {
          const { code, remarks, languageTexts } = item;
          // 覆盖式导入：先删除再插入
          await db.run('DELETE FROM i18n_data WHERE code = ?', [code]);
          for (const text of languageTexts) {
            await db.run(
              'INSERT INTO i18n_data (code, language_tag, message, remarks) VALUES (?, ?, ?, ?)',
              [code, text.languageTag, text.message, remarks]
            );
          }
        }
        await db.run('COMMIT TRANSACTION');
        return { success: true, message: '导入成功', data: { count: records.length } };
      } catch (error) {
        await db.run('ROLLBACK TRANSACTION');
        throw error;
      }
    } catch (error) {
      console.error('导入国际化数据服务错误:', error);
      return { success: false, error: error.message, message: '导入失败，请稍后重试', status: 500 };
    }
  }

  // 导出国际化数据（JSON/CSV）
  async exportI18nData({ format = 'json', languageTags }) {
    try {
      const db = await getDb();
      let query = 'SELECT code, language_tag, message, remarks FROM i18n_data';
      const params = [];
      if (languageTags && Array.isArray(languageTags) && languageTags.length > 0) {
        const placeholders = languageTags.map(() => '?').join(',');
        query += ` WHERE language_tag IN (${placeholders})`;
        params.push(...languageTags);
      }
      const rows = await db.all(query, params);

      if (format === 'csv') {
        const header = 'code,languageTag,message,remarks';
        const lines = rows.map(r => [r.code, r.language_tag, r.message, r.remarks || ''].map(v => {
          const s = String(v ?? '');
          return s.includes(',') ? `"${s.replace(/"/g, '""')}"` : s;
        }).join(','));
        const content = [header, ...lines].join('\n');
        return { success: true, message: '导出成功', data: { format: 'csv', content } };
      }

      // JSON格式：聚合为每个code一个对象
      const map = new Map();
      for (const r of rows) {
        const item = map.get(r.code) || { code: r.code, remarks: r.remarks, languageTexts: [] };
        item.languageTexts.push({ languageTag: r.language_tag, message: r.message });
        map.set(r.code, item);
      }
      const items = Array.from(map.values());
      return { success: true, message: '导出成功', data: { format: 'json', items } };
    } catch (error) {
      console.error('导出国际化数据服务错误:', error);
      return { success: false, error: error.message, message: '导出失败，请稍后重试', status: 500 };
    }
  }
}

module.exports = I18nService;